package org.netconsole.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.netconsole.model.User;

public class UserDAOImpl implements UserDAO {
	
    private SessionFactory sf;

    public UserDAOImpl(SessionFactory sf){
            this.sf = sf;
    }

    @Override
    public User getUserByCredentials(String userId, String password) {
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("from User where id=:id and pwd=:pwd");
            query.setString("id", userId); query.setString("pwd", password);
            User user = (User) query.uniqueResult();
            if(user != null){
                    System.out.println("User Retrieved from DB::"+user);
            }
            tx.commit();session.close();
            return user;
    }

public User getUserByEmail(String email) {
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("from User where email=:email");
            query.setString("email", email);
            User user = (User) query.uniqueResult();
            if(user != null){
                    System.out.println("User Retrieved from DB::"+user);
            }
            tx.commit();session.close();
            return user;
    }

    @Override
    public User insertUser(User user) {

        try{
            Session session = sf.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (Exception e){

        }

        return user;
    }

    @Override
    public List<User> listUsers() {
        List<User> lst = new ArrayList<User>();
        Session session = sf.openSession();
        lst = session.createQuery("from User").list();
        return lst;
    }

}
